package com.witframework.web.filter;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class BufferedHttpServletResponseWrapper extends HttpServletResponseWrapper {
	
	private HttpServletResponse response;
	private CharArrayWriter charWriter;
	private PrintWriter printWriter;
	
	private boolean committed=false;

	public BufferedHttpServletResponseWrapper(HttpServletResponse response)	{
		super(response);
		this.response=response;
		charWriter = new CharArrayWriter();
		printWriter = new PrintWriter(charWriter);
	}

	@Override
	public PrintWriter getWriter(){
		return printWriter;
	}

	public CharArrayWriter getCharWriter(){
		return charWriter;
	}
	protected String getBody() {
        return this.charWriter.toString();
    }
	protected void resetBody(String str) throws IOException {
		charWriter.reset();
        this.charWriter.write(str);
    }	
	public void commit() throws IOException{
		super.flushBuffer();
		if(!committed){
			try{				
				charWriter.writeTo(response.getWriter());			
			}catch(Exception e){}
		}
		committed=true;
	}
	@Override
	public boolean isCommitted() {		
		return committed;
	}

	@Override
	public void resetBuffer() {		
		super.resetBuffer();
		charWriter.reset();
	}
}
